package gulimall.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import gulimall.constant.AuthServerConstant;
import gulimall.vo.MemberRespVO;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登录拦截器
 *
 * @author HLF
 * @date 2022/8/22 21:47
 */
@Component
public class LoginUserInterceptor implements HandlerInterceptor {

    /**
     * 同一个线程共享ThreadLocal中的数据
     */
    public static ThreadLocal<MemberRespVO> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();

        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (attribute != null) {
            ObjectMapper mapper = new ObjectMapper();
            MemberRespVO member = mapper.convertValue(attribute, MemberRespVO.class);
            threadLocal.set(member);
            return true;
        }

        //未登录直接重定向回登录页面
        response.sendRedirect("http://auth.firstgulimall.com/login.html");
        return false;
    }
}
